const db = require('../modules/db')
const md5 = require('blueimp-md5')

//得到登录状态
exports.get = (req, res, next) => {
  const {user} = req.session

  if (!user) {
    return res.status(401).json({
      error: '没人登录'
    })
  }

  res.status(200).json(user)
} 

//修改登录信息
  exports.edit = (req, res, next) => {
    const user = req.body
    req.session.user = user
    if (!user) {
      return res.status(401).json({
        error: '没人登录'
      })
    }

    res.status(200).json(user)
  } 

//创建会话 (登录)
exports.create = async (req, res, next) => {
  try{
    const body = req.body
    body.password =  md5(md5(body.password))
    const sqlStr = `SELECT * FROM users WHERE email = '${body.email}' and password = '${body.password}'`
    const [user] = await db.query(sqlStr)
    
    //判断有没有找到
    if (!user) {
      return res.status(404).json({
      error: '用户不存在'
    })
    }

    req.session.user = user
    res.status(201).json(user)
  } catch (err) {
    next(500)
  }

} 

//销毁会话状态,退出登录
exports.delete = (req, res, next) => {
  delete req.session.user 
  res.status(200).json({})
} 